const request = (options) => {
  const app = getApp();
  const token = wx.getStorageSync('token');

  return new Promise((resolve, reject) => {
    wx.request({
      ...options,
      url: `${app.globalData.baseUrl}${options.url}`,
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 401) {
          // token过期，跳转到登录页
          wx.redirectTo({
            url: '/pages/login/login'
          });
          reject(new Error('未授权'));
        } else {
          resolve(res.data);
        }
      },
      fail: reject
    });
  });
};

export default request; 